import wave
import sounddevice as sd
from vosk import Model, KaldiRecognizer
import json
import os

class AudioConfig:
    def __init__(self, filename="my_recording.wav", duration=5, sample_rate=16000):
        self.filename = filename
        self.duration = int(duration)  # 确保duration为整数
        self.sample_rate = int(sample_rate)  # 确保sample_rate为整数

def record_audio(config):
    print("开始录音...")
    try:
        # 确保参数为整数类型
        duration = int(config.duration)
        sample_rate = int(config.sample_rate)
        
        audio_data = sd.rec(int(duration * sample_rate), 
                          samplerate=sample_rate, 
                          channels=1, 
                          dtype='int16')
        sd.wait()
        with wave.open(config.filename, 'wb') as wf:
            wf.setnchannels(1)
            wf.setsampwidth(2)  # 16-bit PCM
            wf.setframerate(sample_rate)
            wf.writeframes(audio_data.tobytes())
        print("录音已保存为:", config.filename)
    except ValueError as e:
        print("错误：请确保duration和sample_rate为有效的数字")
        raise
    except Exception as e:
        print("录音过程中发生错误:", str(e))
        raise

def local_asr(audio_file):
    # 加载模型

    model_path=r'C:\vosk-model-cn-0.1'
    model = Model(model_path)
    recognizer = KaldiRecognizer(model, 16000)
    result = {"text": ""}  # 初始化result

    # 读取音频文件
    with wave.open(audio_file, 'rb') as wf:
        while True:
            data = wf.readframes(4000)
            if len(data) == 0:
                break
            if recognizer.AcceptWaveform(data):
                result = json.loads(recognizer.Result())
                print("识别结果:", result.get("text", ""))
        
        # 获取最终结果
        final_result = json.loads(recognizer.FinalResult())
        if final_result.get("text", ""):
            result = final_result

    return result.get("text", "")